//
//  RouMediaChoice.swift
//  ONESwift
//
//  Created by wangkun on 2017/7/16.
//  Copyright © 2017年 wangkun. All rights reserved.
//

import UIKit
import MobileCoreServices
import AssetsLibrary

public enum MediaChoiceType {
    case image
//    case movie
//    case all
}

public class RouMediaChoice: NSObject {
    
    public typealias MediaCholceBlock = (_ image: UIImage, _ moviePath: String) -> Void
    public static let shared : RouMediaChoice = {
        return RouMediaChoice()
    }()
    public var videoLong: TimeInterval = 0
    
    fileprivate var statusBarStyle = UIStatusBarStyle.default
    fileprivate var viewController: UIViewController!
    fileprivate var type: MediaChoiceType!
    fileprivate var mediaEdit: Bool!
    fileprivate var choiceBlock: MediaCholceBlock?
    
    public func selectMedia(_ viewController: UIViewController, type: MediaChoiceType = .image, isEdit: Bool = false, block: @escaping MediaCholceBlock) {
        statusBarStyle = application.statusBarStyle
        application.statusBarStyle = .default
        
        self.viewController = viewController
        self.type = type
        self.mediaEdit = isEdit
        self.choiceBlock = block
        
        let actionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "相册", "相机")
        actionSheet.show(in: viewController.view)
    }
    
}

extension RouMediaChoice: UIActionSheetDelegate {
    public func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) {
        if buttonIndex != actionSheet.cancelButtonIndex {
            let picker = UIImagePickerController()
            
            let textAttributes = [NSAttributedStringKey.foregroundColor: UIColor.black]
            picker.navigationBar.titleTextAttributes = textAttributes
            picker.navigationBar.tintColor = UIColor.black
            
            picker.videoQuality = .type640x480
            picker.delegate = self
            
            picker.allowsEditing = mediaEdit
            if videoLong > 0 {
                picker.videoMaximumDuration = videoLong
            }
            
            if type == .image {
                picker.mediaTypes = [(kUTTypeImage as String)]
            }
//            if type == .movie {
//                picker.mediaTypes = [(kUTTypeMovie as String)]
//            }
//            if type == .all {
//                picker.mediaTypes = [(kUTTypeImage as String), (kUTTypeMovie as String)]
//            }
            
            if buttonIndex == 1 {//相机
                picker.sourceType = .photoLibrary
            }
            
            if buttonIndex == 2 {//相册
                let isCamera = UIImagePickerController.isCameraDeviceAvailable(.rear)
                if (!isCamera) {
                    viewController.view.hudShow("没有找到摄像头")
                    return
                }
                
                picker.sourceType = .camera
                picker.modalTransitionStyle = .coverVertical
            }
            viewController.present(picker, animated: true, completion: nil)
        }
    }
}

extension RouMediaChoice: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        let mediaType = info[UIImagePickerControllerMediaType] as? String
        if mediaType == "public.image" {//图片
            let image = (info[UIImagePickerControllerOriginalImage] as? UIImage) ?? UIImage()
            picker.dismiss(animated: true, completion: {
                application.statusBarStyle = self.statusBarStyle
                self.choiceBlock?(image, "")
            })
        }
        if mediaType == "public.movie" {
//            let url = info[UIImagePickerControllerMediaURL]
//            let image = self.thumbnailImage(url)
//            [self compressVideo:url andSave:YES successCompress:^(NSData *data) {
//                [UIApplication.sharedApplication setStatusBarStyle:statusBarStyle];
//                [picker dismissViewControllerAnimated:YES completion:^(void){
//                if (self.imgSelBlock) {
//                self.imgSelBlock(image, moviePath);
//                }
//                }];
//                }];
        }
    }
    
    public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    /// 获取视频缩略图
    ///
    /// - Parameter url: 图片链接
//    func thumbnailImage(_ url: URL) -> UIImage {
//        NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
//        AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
//        // 根据asset构造一张图
//        AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
//        // 设定缩略图的方向
//        // 如果不设定，可能会在视频旋转90/180/270°时，获取到的缩略图是被旋转过的，而不是正向的（自己的理解）
//        generator.appliesPreferredTrackTransform = YES;
//        // 设置图片的最大size(分辨率)
//        generator.maximumSize = CGSizeMake(600, 450);
//        NSError *error = nil;
//        // 根据时间，获得第N帧的图片
//        // CMTimeMake(a, b)可以理解为获得第a/b秒的frame
//        CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(0, 10000) actualTime:NULL error:&error];
//        UIImage *image = [UIImage imageWithCGImage:img];
//        return image;
//    }
    
    /// 压缩视频
    ///
    /// - Parameters:
    ///   - path: 视频地址
    ///   - save: 是否保存本地
    ///   - block: <#block description#>
//    func compressVideo(_ path: URL, _ save: Bool, block: (_ data: NSData) -> Void) {
//        let movieName = String(format: "%d", Date().timeIntervalSince1970)
//        let avAsset = AVURLAsset(url: path)
//        
//        let exportSession = AVAssetExportSession(asset: avAsset, presetName: AVAssetExportPresetMediumQuality)
//        if exportSession != nil {
//            let string = "\(documentPath)/\(movieName)"
//            exportSession.outputURL = [self compressedURL];//设置压缩后视频流导出的路径
//            exportSession.shouldOptimizeForNetworkUse = true;
//            //转换后的格式
//            exportSession.outputFileType = AVFileTypeMPEG4;
//            //异步导出
//            [exportSession exportAsynchronouslyWithCompletionHandler:^{
//                // 如果导出的状态为完成
//                if ([exportSession status] == AVAssetExportSessionStatusCompleted){
//                //                [self saveVideo:[self compressedURL]];//保存视频到相册
//                //压缩成功视频流回调回去
//                NSData *data = [NSData dataWithContentsOfURL:[self compressedURL]];
//                successCompress((data.length > 0) ? data : nil);
//                } else {
//                //压缩失败的回调
//                successCompress(nil);
//                }
//                }];
//        }
//        exportSession.outputURL = [self compressedURL];//设置压缩后视频流导出的路径
//        exportSession.shouldOptimizeForNetworkUse = true;
//        //转换后的格式
//        exportSession.outputFileType = AVFileTypeMPEG4;
//        //异步导出
//        [exportSession exportAsynchronouslyWithCompletionHandler:^{
//            // 如果导出的状态为完成
//            if ([exportSession status] == AVAssetExportSessionStatusCompleted){
//            //                [self saveVideo:[self compressedURL]];//保存视频到相册
//            //压缩成功视频流回调回去
//            NSData *data = [NSData dataWithContentsOfURL:[self compressedURL]];
//            successCompress((data.length > 0) ? data : nil);
//            } else {
//            //压缩失败的回调
//            successCompress(nil);
//            }
//            }];
//    }
    
    /// 视频保存到相册
    ///
    /// - Parameter url: 视频地址
//    func saveVideo(url: URL) {
//        let library = ALAssetsLibrary()
//        library.writeVideoAtPath(toSavedPhotosAlbum: url) { (url: URL?, error: Error?) in
//            if error != nil {
//                
//            }
//        }
//    }
}
